package com.dylon.imgOperate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class BufferedImageTest {
	
	public static void main(String[] args) {
		
		// 图片路径
		String imageURL = "https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=3101694723,748884042&os=1763536506,877714758&simid=3371250864,260556217&pn=7&rn=1&di=22110&ln=1698&fr=&fmq=1625542653765_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fcdn.duitang.com%252Fuploads%252Fblog%252F201306%252F25%252F20130625150506_fiJ2r.jpeg%26refer%3Dhttp%253A%252F%252Fcdn.duitang.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1628134654%26t%3D415d15ba446166f15299f9e729380707&rpstart=0&rpnum=0&adpicid=0&nojc=undefined";
		
		BufferedImage image = getRemoteBufferedImage(imageURL);
		if (image != null) {
			System.out.println("BufferedImage的高度: " + image.getHeight());
			System.out.println("BufferedImage的宽度: " + image.getWidth());
		} else {
			System.out.println("BufferedImage图片不存在!");
		}
	}
 
	/**
	 * 获取远程网络图片信息
	 * @param imageURL
	 * @return
	 */
	public static BufferedImage getRemoteBufferedImage(String imageURL) {
		URL url = null;
		InputStream is = null;
		BufferedImage bufferedImage = null;
		try {
			url = new URL(imageURL);
			is = url.openStream();
			bufferedImage = ImageIO.read(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println("imageURL: " + imageURL + ",无效!");
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("imageURL: " + imageURL + ",读取失败!");
			return null;
		} finally {
			try {
				if(is!=null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("imageURL: " + imageURL + ",流关闭异常!");
				return null;
			}
		}
		return bufferedImage;
	}

	
}